package com.voice.server.job;

import com.voice.server.connection.ConnectionInvoke;
import com.voice.server.entity.Device;
import com.voice.server.repository.DeviceRepository;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DeviceWorkScheduler implements InitializingBean {

    @Autowired
    private ConnectionInvoke connectionInvoke;
    @Autowired
    private DeviceRepository deviceRepository;
    private Scheduler scheduler;
    private JobDetail jobDetail;
    public static String startWorkTopic="device_start_work";
    public static String finishWorkTopic="device_finish_work";

    @Override
    public void afterPropertiesSet() throws Exception {
        this.scheduler = new StdSchedulerFactory().getScheduler();
        this.scheduler.start();
        JobDataMap jobDataMap=new JobDataMap();
        jobDataMap.put("connectionInvoke",connectionInvoke);
        this.jobDetail= JobBuilder.newJob(DeviceWorkJob.class).setJobData(jobDataMap).storeDurably(true).build();
        this.scheduler.addJob(jobDetail,true);
        List<Device> list=deviceRepository.findByStartTimeIsNotBlank();
        for(Device device:list){
            String[] startTime=device.getStartTime().split(":");
            String[] endTime=device.getEndTime().split(":");
            startWorkScheduler(device.getUserId(),device.getDeviceKey(),Integer.parseInt(startTime[0]),Integer.parseInt(startTime[1]));
            endWorkScheduler(device.getUserId(),device.getDeviceKey(),Integer.parseInt(endTime[0]),Integer.parseInt(endTime[1]));
        }
    }

    public void startWorkScheduler(String userId,String deviceKey,int hour,int minute) throws SchedulerException {
        scheduler(userId,deviceKey,hour,minute,startWorkTopic);
    }

    public void startWorkScheduler(String userId,String deviceKey) throws SchedulerException {
        scheduler(userId,deviceKey,startWorkTopic);
    }

    public void endWorkScheduler(String userId,String deviceKey,int hour,int minute) throws SchedulerException {
        scheduler(userId,deviceKey,hour,minute,finishWorkTopic);
    }

    public void endWorkScheduler(String userId,String deviceKey) throws SchedulerException {
        scheduler(userId,deviceKey,finishWorkTopic);
    }

    public void scheduler(String userId,String deviceKey,int hour,int minute,String topic) throws SchedulerException{
        TriggerKey triggerKey=new TriggerKey(deviceKey+topic,userId);
        Trigger trigger= TriggerBuilder.newTrigger()
                .withIdentity(deviceKey+topic,userId)
                .usingJobData("topic",topic)
                .usingJobData("deviceKey",deviceKey)
                .forJob(jobDetail)
                .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(hour,minute))
                .build();
        if(scheduler.getTrigger(triggerKey)==null){
            scheduler.scheduleJob(trigger);
        }else {
            scheduler.rescheduleJob(triggerKey,trigger);
        }
    }

    public void scheduler(String userId,String deviceKey,String topic) throws SchedulerException{
        TriggerKey triggerKey=new TriggerKey(deviceKey+topic,userId);
        Trigger trigger= TriggerBuilder.newTrigger()
                .withIdentity(deviceKey+topic,userId)
                .usingJobData("topic",topic)
                .usingJobData("deviceKey",deviceKey)
                .forJob(jobDetail)
                .startNow()
                .build();
        if(scheduler.getTrigger(triggerKey)==null){
            scheduler.scheduleJob(trigger);
        }else {
            scheduler.rescheduleJob(triggerKey,trigger);
        }
    }
}
